package com.gjt.http;

import java.io.IOException;
import java.net.*;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created with Intel IDEA.
 * 内存中ResponseCache : 请求时存储和获取缓存的值同时注意原来的Cache-control首部
 *          安装或者更换缓存的工厂静态方法 ：
 *                          public static ResponseCache getDefault();
 *                          public static void setDefault(ResponseCache responseCache);
 * java中要求一次只能有一个URL缓存
 * @Auther: gjt
 * @Date: 2024/3/27 17:49
 */
public class MemoryCache extends ResponseCache {
    private final Map<URI,SimpleCacheResponse> responses = new ConcurrentHashMap<>();
    private final int maxEntries;

    public MemoryCache() {
        this(100);
    }

    public MemoryCache(int maxEntries){
        this.maxEntries = maxEntries;
    }
    @Override
    public CacheResponse get(URI uri, String rqstMethod, Map<String, List<String>> rqstHeaders) throws IOException {
        if("GET".equals(rqstMethod)){
            SimpleCacheResponse response = responses.get(uri);
            // 检查过期时间
            if(response != null && response.isExpired()){
                responses.remove(response);
                response = null;
            }
            return response;
        }else {
            return  null;
        }
    }

    @Override
    public CacheRequest put(URI uri, URLConnection conn) throws IOException {
        if(responses.size() >= maxEntries) return null;
        CachedControl control = new CachedControl(conn.getHeaderField("Cache-Control"));
        if(control.isNoCache()){
            return null;
        } else if (!conn.getHeaderField(0).startsWith("GET")) {
            // 只缓存GET
            return null;
        }
        SimpleCacheRequest request = new SimpleCacheRequest();
        SimpleCacheResponse response = new SimpleCacheResponse(request, conn, control);

        responses.put(uri,response);
        return request;
    }
}
